package com.iting.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author Nie ZhiPeng
 */
@RequestMapping("/file")
@Controller
public class FlieController {
	@GetMapping
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		File sourceFile = new File("E:\\abc.jpg");
		FileInputStream fileInputStream = new FileInputStream(sourceFile);
		ServletOutputStream outputStream = response.getOutputStream();
		response.setHeader("Content-Disposition","attachment;filename="+convertToFileName(request,"聂志鹏.jpg"));
		byte[] bytes = new byte[1024];
		int len;
		while ((len = fileInputStream.read(bytes)) != -1){
			outputStream.write(bytes,0,len);
		}
	}

	public static String convertToFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
		// 针对IE或者以IE为内核的浏览器：
		String userAgent = request.getHeader("User-Agent");
		if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
			fileName = URLEncoder.encode(fileName, "UTF-8");
		} else {
			// 非IE浏览器的处理：  
			fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
		}
		return fileName;
	}
}
